<template>
  <div id="down-box" class="markdown-box">
    <md-editor
      v-model="mdProps.context"
      showCodeRowNumber
      :previewOnly="mdProps.previewOnly"
      :editorId="mdProps.editorId"
      :extensions="[MarkExtension]"
      :marked-heading="markedHeading"
      :style="mdProps.style ? mdProps.style : style"
    />
    <div class="toc-container">
      <div class="toc"></div>
    </div>
  </div>
</template>

<script setup>
  import MdEditor from 'md-editor-v3'
  import 'md-editor-v3/lib/style.css'
  import { tocbot, getBoxHeight } from '@/utils/tocbot'

  // 使用
  // import sanitizeHtml from 'sanitize-html'

  import { nextTick, onUnmounted, onUpdated } from 'vue'

  defineProps({
    //获取传参的数据
    mdProps: {
      type: Object
    }
  })

  const style = {
    background: 'rgb(255 255 255 / 0%) !important',
    color: 'var(--font-color)'
  }

  // @onGetCatalog="onGetCatalog"
  // const onGetCatalog = (e) => {

  // }

  //识别mark 引用
  const MarkExtension = {
    name: 'MarkExtension',
    level: 'inline',
    start: (text) => text.match(new RegExp('==[^==]'))?.index,
    tokenizer(text) {
      const reg = new RegExp('^==([^==]*)==')
      const match = reg.exec(text)
      if (match) {
        return {
          type: 'MarkExtension',
          raw: match[0],
          text: match[1].trim(),
          tokens: []
        }
      }
    },
    renderer(token) {
      return `<mark>${token.text}</mark>`
    }
  }

  const markedHeading = (text, level, raw) => {
    // 你不能直接调用默认的markedHeadingId，但是它很简单
    // 如果你的id与raw不相同，请一定记得将你的生成方法通过markedHeadingId告诉编辑器
    // 否则编辑器默认的目录定位功能无法正确使用
    const id = raw

    if (new RegExp('<a.*>.*<\\/a>').test(text)) {
      return `<h${level} id="${id}">${text.replace(
        new RegExp('(?<=\\<a.*)>(?=.*<\\/a>)'),
        'target="_blank">'
      )}</h${level}>`
    } else if (text !== raw) {
      return `<h${level} id="${id}">${text}</h${level}>`
    } else {
      return `<h${level} id="${id}">${raw}</h${level}>`
    }
  }

  //xss
  // const sanitize = (html) => {
  //   return sanitizeHtml(html)
  // }

  onUpdated(() => {
    nextTick(() => {
      getBoxHeight()
    })
    tocbot.refresh()
  })

  onUnmounted(() => {
    tocbot.destroy()
  })

  nextTick(() => {
    //删除markdown复制评论渲染多个问题
    $(function () {
      $('.comment pre').each((index, element) => {
        let i = 0
        element.childNodes.forEach((item) => {
          if (i++ >= 2) {
            item.remove()
          }
        })
      })
    })
  })
</script>

<style lang="less" scoped>
  .markdown-box {
    position: relative;
  }
</style>
